package com.forlgb.powercloud.netty4.all.server;

import com.forlgb.powercloud.netty4.all.common.pojo.FileUploadFile;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Properties;

import static com.forlgb.powercloud.netty4.all.common.util.PropertiesUtils.getProperties;

@Slf4j
public class FileUploadServerHandler extends ChannelInboundHandlerAdapter {

    private int byteRead;

    private volatile int start = 0;

    private static String file_dir;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        super.channelActive(ctx);
        log.info("服务端：channelActive()");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        try {
            super.channelInactive(ctx);
            log.info("服务端：channelInactive()");
        } finally {
            ctx.flush();
            ctx.close();
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        setBasicData();
        if (msg instanceof FileUploadFile) {
            FileUploadFile fileUploadFile = (FileUploadFile) msg;
            byte[] bytes = fileUploadFile.getBytes();
            byteRead = fileUploadFile.getEndPos();
            //文件名
            String fileName = fileUploadFile.getFile_md5();
            String path = file_dir + File.separator + fileName;
            File file = new File(path);
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            randomAccessFile.seek(start);
            randomAccessFile.write(bytes);
            start = start + byteRead;
            log.info("path:" + path + "," + byteRead);
            if (byteRead > 0) {
                ctx.writeAndFlush(start);
                randomAccessFile.close();
                if(byteRead!=1024 * 10){
                    Thread.sleep(1000);
                    channelInactive(ctx);
                }
            }else {
                log.info("文件传输完毕");
                ctx.close();
            }
        } else {
            log.info("文件错误");
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
        log.info("文件传输出现异常");
    }

    private static void setBasicData() throws IOException {
        Properties properties = getProperties("/server.properties");
        file_dir = String.valueOf(properties.get("tcp.server.file-dir"));
    }
}
